package dongze.com.ckdj.fragment;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dongze.com.ckdj.R;
import dongze.com.ckdj.activity.InspectionActivity;
import dongze.com.ckdj.adapter.StringArrayAdapter;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import dongze.com.ckdj.event.RefreshEvent;
import dongze.com.ckdj.util.MyLog;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/7/21.
 */

public class CheckInRecordFragment extends ProcessableFragment {
    private static final String TAG = CheckInRecordFragment.class.getSimpleName();
    private static int CHECK_IN_OPERATION_REQUEST = 9999;
    @BindView(R.id.record_list)
    ListView mRecordList;

    @Inject
    InspectionSectionResponse mInspectionSection;
    @Inject
    VehicleInformationDetail mVehicleInformationDetail;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else {
            getFragmentManager().beginTransaction().remove(this).commit();
            return;
        }


        loadRecords();
    }

    @Nullable
    @Override
    protected View createContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_check_in_record, container, false);
        ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CHECK_IN_OPERATION_REQUEST && resultCode == Activity.RESULT_OK) {
            loadRecords();
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick(R.id.new_record)
    void newRecord(View view) {
        MyLog.d(TAG, "newRecord: ");
        if (checkOperationLoaded()) {
            startActivityForResult(new Intent(getActivity().getApplicationContext(), InspectionActivity.class), CHECK_IN_OPERATION_REQUEST);
        }
    }

    @OnClick(R.id.delete_record)
    void deleteRecord(View view) {
        MyLog.d(TAG, "deleteRecord: ");
        if (checkOperationLoaded()) {
            // TODO: 2017/7/31
        }
    }

    private void loadRecords() {
        if (mInspectionSection != null) {
            doProcessing();
            mapUtil.getInspectionSectionRecords(
                    mVehicleInformationDetail.getVin(),
                    mInspectionSection.getNode_code(),
                    new DisposableObserver<List<Pair<String, String>>>() {
                        @Override
                        public void onNext(final List<Pair<String, String>> value) {
                            String[] list = new String[value.size()];

                            for (int i = 0; i < list.length; i++) {
                                list[i] = value.get(i).second;
                            }

                            fillRecordList(list);
                            mRecordList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    loadDetail(value.get(position).first);
                                }
                            });
                        }

                        @Override
                        public void onError(Throwable e) {
                            finishProcessing();
                            new AlertDialog.Builder(getContext())
                                    .setTitle("错误")
                                    .setMessage("加载点检记录失败！！！")
                                    .create()
                                    .show();
                        }

                        @Override
                        public void onComplete() {
                            finishProcessing();
                        }
                    });
        }
    }

    private void fillRecordList(String[] list) {
        mRecordList.setAdapter(new StringArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, list));
    }

    private void loadDetail(String id) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(getActivity().getApplicationContext(), InspectionActivity.class));
        intent.putExtra("id", id);
        startActivity(intent);
    }

    private boolean checkOperationLoaded() {
        if (mInspectionSection == null) {
            new AlertDialog.Builder(getContext())
                    .setTitle("错误")
                    .setMessage("请先选择点检环节")
                    .create()
                    .show();
            return false;
        }

        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe
    public void refresh(RefreshEvent event) {
        if (event.isNeedRefresh()) {
            loadRecords();
        }

    }
}
